package com.innovation.client;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import com.innovation.config.GlobalConfig;
import com.innovation.config.MessageConfig;
import com.innovation.config.GlobalConfig.ServerConfig;
import com.innovation.config.GlobalConfig.ZoneConfig;
import com.innovation.message.ServerCmdProto.ServerCmd;
import com.innovation.message.ServerMessageProto.ServerMessage;
import com.innovation.util.MessageUtil;

public class ClientSet {
	
	public static final ClientSet INSTANCE = new ClientSet();
	
	private ClientSet(){
		
	}
	
	/**
	 * GameServer的连接池
	 */
	private Map<Integer, ClientPool> gameServerClientMap = new HashMap<Integer, ClientPool>();
	
	/**
	 * FightServer的连接池
	 */
	private Map<Integer, ClientPool> fightServerClientMap = new HashMap<Integer, ClientPool>();
	
	/**
	 * 初始化与各GameServer之间的连接
	 */
	public void initGameServerClient(){
		Map<Integer, ZoneConfig> map = GlobalConfig.getZoneConfigMap();
		for(Entry<Integer, ZoneConfig> entry : map.entrySet()){
			ZoneConfig config = entry.getValue();
			ClientPool clientPool = new ClientPool();
			clientPool.init(config.host, config.socketPort, 5120, 5120);
			gameServerClientMap.put(config.zoneId, clientPool);
		}
	}
	
	/**
	 * 初始化与各FightServer之间的连接
	 */
	public void initFightServerClient(){
		Map<Integer, ServerConfig> map = GlobalConfig.getFightServerConfigMap();
		for(Entry<Integer, ServerConfig> entry : map.entrySet()){
			ServerConfig config = entry.getValue();
			ClientPool clientPool = new ClientPool();
			clientPool.init(config.host, config.socketPort, 5120, 5120);
			fightServerClientMap.put(config.id, clientPool);
		}
	}
	
	/**
	 * 向GameServer发送数据，并接收响应数据
	 * @param zoneId
	 * @param msg
	 * @return
	 */
	public ServerMessage send2GameServer(ServerMessage msg){
		ClientPool pool = gameServerClientMap.get(msg.getServerId());
		return pool.sendAndRecv(msg);
	}
	
	/**
	 * 向FightServer发送数据，并接收响应数据
	 * @param id
	 * @param msg
	 * @return
	 */
	public ServerMessage send2FightServer(ServerMessage msg){
		ClientPool pool = fightServerClientMap.get(msg.getServerId());
		return pool.sendAndRecv(msg);
	}
	
	public static void main(String[] args) throws Exception {
		
		GlobalConfig.init();
		//提示信息初始化
		MessageConfig.init();
		
		ClientSet.INSTANCE.initFightServerClient();
		
		ServerMessage.Builder msg = MessageUtil.buildServerMsg(0, 0, ServerCmd.CMD_PARTICIPATE_PVP_VALUE);
		/*PVPPlayerMsg.Builder playerMsg = PVPPlayerMsg.newBuilder();
		playerMsg.setServerId(0);
		playerMsg.setPlayerId(84);
		playerMsg.setPlayerName("test1");
		playerMsg.setPlayerLevel(90);
		playerMsg.setPvpScore(0);
		msg.setData(playerMsg.build().toByteString());*/
		ServerMessage result = ClientSet.INSTANCE.send2FightServer(msg.build());
		System.out.println(result);
	}
}
